package service

import (
	"context"
	"sync"
	"time"

	pb "user/api/ws/v1"

	"user/internal/data"

	"github.com/gorilla/websocket"
)

// 内存存储用户连接和消息（仅演示用，生产环境请用数据库和分布式缓存）
var (
	// 用户ID到WebSocket连接
	userConnStore = struct {
		sync.RWMutex
		conns map[string]*websocket.Conn
	}{conns: make(map[string]*websocket.Conn)}

	// 聊天消息存储
	messageStore = struct {
		sync.RWMutex
		data map[string][]*pb.MessageItem // key: chatID, value: messages
	}{data: make(map[string][]*pb.MessageItem)}
)

// 生成一对一聊天的唯一chatID（无序，user1_user2和user2_user1相同）
func getChatID(user1, user2 string) string {
	if user1 < user2 {
		return user1 + "_" + user2
	}
	return user2 + "_" + user1
}

type ChatServiceService struct {
	pb.UnimplementedChatServiceServer
	Repo *data.ChatRepo
}

func NewChatServiceService(repo *data.ChatRepo) *ChatServiceService {
	return &ChatServiceService{Repo: repo}
}

// 发送消息（通过WebSocket推送给对方）
func (s *ChatServiceService) SendMessage(ctx context.Context, req *pb.SendMessageRequest) (*pb.SendMessageReply, error) {
	if req.SenderId == "" || req.ReceiverId == "" || req.Message == nil {
		return &pb.SendMessageReply{Code: 1, Message: "invalid request"}, nil
	}
	msg := &pb.MessageItem{
		MessageId:  time.Now().Format("20060102150405.000000"),
		SenderId:   req.SenderId,
		ReceiverId: req.ReceiverId,
		Message:    req.Message,
		Timestamp:  req.Timestamp,
	}
	s.Repo.SaveMessage(msg)
	return &pb.SendMessageReply{
		MessageId: msg.MessageId,
		Code:      0,
		Message:   "ok",
	}, nil
}

// 获取消息历史

func (s *ChatServiceService) GetMessageHistory(ctx context.Context, req *pb.GetMessageHistoryRequest) (*pb.GetMessageHistoryReply, error) {
	// 参数验证
	if req.UserId_1 == "" || req.UserId_2 == "" {
		return &pb.GetMessageHistoryReply{
			Code:    1,
			Message: "user_id_1 and user_id_2 are required",
		}, nil
	}

	// 分页参数验证和默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 20
	}
	if req.PageSize > 100 {
		req.PageSize = 100 // 限制最大页大小
	}

	msgs, total := s.Repo.GetHistory(req.UserId_1, req.UserId_2, req.Page, req.PageSize)

	return &pb.GetMessageHistoryReply{
		Messages: msgs,
		Total:    total,
		Code:     0,
		Message:  "ok",
	}, nil
}

// GetMessageHistoryByTimeRange 按时间范围获取消息历史
func (s *ChatServiceService) GetMessageHistoryByTimeRange(ctx context.Context, req *pb.GetMessageHistoryByTimeRangeRequest) (*pb.GetMessageHistoryReply, error) {
	// 参数验证
	if req.UserId_1 == "" || req.UserId_2 == "" {
		return &pb.GetMessageHistoryReply{
			Code:    1,
			Message: "user_id_1 and user_id_2 are required",
		}, nil
	}

	// 时间范围验证
	if req.StartTime <= 0 || req.EndTime <= 0 || req.StartTime >= req.EndTime {
		return &pb.GetMessageHistoryReply{
			Code:    1,
			Message: "invalid time range",
		}, nil
	}

	// 限制数量
	limit := req.Limit
	if limit <= 0 {
		limit = 50
	}
	if limit > 200 {
		limit = 200
	}

	msgs, err := s.Repo.GetHistoryByTimeRange(req.UserId_1, req.UserId_2, req.StartTime, req.EndTime, limit)
	if err != nil {
		return &pb.GetMessageHistoryReply{
			Code:    1,
			Message: "query failed: " + err.Error(),
		}, nil
	}

	return &pb.GetMessageHistoryReply{
		Messages: msgs,
		Total:    int32(len(msgs)),
		Code:     0,
		Message:  "ok",
	}, nil
}

// GetUnreadMessageCount 获取用户未读消息数量
func (s *ChatServiceService) GetUnreadMessageCount(ctx context.Context, req *pb.GetUnreadMessageCountRequest) (*pb.GetUnreadMessageCountReply, error) {
	if req.UserId == "" {
		return &pb.GetUnreadMessageCountReply{
			Code:    1,
			Message: "user_id is required",
		}, nil
	}

	count, err := s.Repo.GetUnreadCount(req.UserId)
	if err != nil {
		return &pb.GetUnreadMessageCountReply{
			Code:    1,
			Message: "query failed: " + err.Error(),
		}, nil
	}

	return &pb.GetUnreadMessageCountReply{
		Count:   count,
		Code:    0,
		Message: "ok",
	}, nil
}

// 检查用户是否在线
func (s *ChatServiceService) CheckUserOnline(ctx context.Context, req *pb.CheckUserOnlineRequest) (*pb.CheckUserOnlineReply, error) {
	isOnline := s.Repo.IsOnline(req.UserId)
	return &pb.CheckUserOnlineReply{
		IsOnline: isOnline,
		Code:     0,
		Message:  "ok",
	}, nil
}
